package web

import (
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
)

// EPController enterprise-park控制器
type EPController struct {
	EnterpriseBll        *bll.Enterprise      `inject:""`
	EntranceEquipmentBll *bll.EEBll           `inject:""`
	ParkBll              *bll.Park            `inject:""`
	EnterpriseParkBll    *bll.EnterprisePark  `inject:""`
	ParkEntranceBll      *bll.ParkEntranceBll `inject:""`
}

// QueryPage 查询分页
func (a *EPController) QueryPage(ctx *context.Context) error {
	ctx.WriteOperateLog("EPController.QueryPage", "企业门禁管理-查询分页数据")
	//获取参数
	params := new(schema.EnterpriseQueryParam)
	pageIndex := ctx.GetPageIndex()
	pageSize := ctx.GetPageSize()
	params.Name = ctx.Query("enterprise_name")
	params.Contacts = ctx.Query("contacts")
	params.ContactTel = ctx.Query("contact_tel")
	params.Address = ctx.Query("enterprise_address")
	params.EntryTimeStart = ctx.QueryInt64("admission_start_time")
	params.EntryTimeEnd = ctx.QueryInt64("admission_end_time")
	//查询列表
	total, items, err := a.EnterpriseBll.QueryPage(params, pageIndex, pageSize)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	//获取企业分类
	var category []map[string]string
	category, err = a.EnterpriseBll.QueryCategory()
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	fmt.Println("category:", category)
	list := make([]map[string]interface{}, 0)
	for _, value := range items {
		item := make(map[string]interface{})
		item["record_id"] = value.RecordID
		item["enterprise_name"] = value.Name
		item["contacts"] = value.Contacter
		item["contact_tel"] = value.ContactTel
		item["enterprise_address"] = value.Address
		item["admission_time"] = value.EntryTime
		item["migration_time"] = value.MigrationTime
		item["state"] = value.Status
		//对应企业所属行业

		for _, perMap := range category {
			if perMap["record_id"] == value.Category {
				item["enterprise_type"] = perMap["name"]
				break
			}
		}
		list = append(list, item)
	}
	result := map[string]interface{}{
		"list": list,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  pageIndex,
			"pageSize": pageSize,
		},
	}
	return ctx.ResSuccess(result)
}

// Get 查询
func (a *EPController) Get(ctx *context.Context) error {
	ctx.WriteOperateLog("EPController.Get", "企业门禁管理-查询企业门禁设备")
	enterpriseID := ctx.Param("id")
	var (
		enterprisePark         *schema.EnterprisePark
		entranceAvailableItems []*schema.EntranceEquipment
		err                    error
	)
	//	获取企业的门牌
	enterprisePark, err = a.EnterpriseParkBll.Get(enterpriseID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	//	盛放所有父节点数组
	allFatherNodes := make([]string, 0)
	for _, nodeID := range enterprisePark.Nodes {
		fatherNodes, err := a.ParkBll.QueryAllParentID(nodeID, true)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
		allFatherNodes = append(allFatherNodes, fatherNodes...)
	}
	//	对数组去重
	tempMap := make(map[string]int)
	for _, node := range allFatherNodes {
		tempMap[node] = 1
	}
	queryNodes := make([]string, 0)
	for node := range tempMap {
		queryNodes = append(queryNodes, node)
	}
	//	查询门牌-门禁设备 对应关系
	parkEntranceArray, err := a.ParkEntranceBll.GetByArray(queryNodes)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	//	收集门禁设备id
	tempEntranceArray := make([]string, 0)
	for _, item := range parkEntranceArray {
		tempEntranceArray = append(tempEntranceArray, item.Entrances...)
	}
	//	对上面的数组去重
	tempEntranceMap := make(map[string]int)
	for _, entranceID := range tempEntranceArray {
		tempEntranceMap[entranceID] = 1
	}
	queryEntranceIDS := make([]string, 0)
	for entranceID := range tempEntranceMap {
		queryEntranceIDS = append(queryEntranceIDS, entranceID)
	}

	resultArray := make([]map[string]interface{}, 0)

	//	门禁设备
	if len(queryEntranceIDS) > 0 {
		//	批量查询门禁设备
		entranceAvailableItems, err = a.EntranceEquipmentBll.QueryEntranceArray(queryEntranceIDS)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
		for _, item := range entranceAvailableItems {
			itemMap := make(map[string]interface{})
			itemMap["record_id"] = item.RecordID
			itemMap["equipment_id"] = item.EquipmentID
			itemMap["equipment_name"] = item.EquipmentName
			itemMap["equipment_type"] = item.EquipmentType
			itemMap["guard_zone_type"] = item.GuardZoneType
			itemMap["note"] = item.Memo
			//	根据门禁id 获取建筑节点和门禁对应关系
			parkEntrances, err := a.ParkEntranceBll.GetByEntranceID(item.RecordID)
			if err != nil {
				return ctx.ResErrInternalServer(err)
			}
			//	构造管控区域名称
			itemMap["guard_zone_name"] = ""
			var guardZoneName string
			for _, parkEntrance := range parkEntrances {
				fullName, err := a.ParkBll.QueryFullName(parkEntrance.NodeID)
				if err != nil {
					return ctx.ResErrInternalServer(err)
				}
				guardZoneName += fullName
			}
			itemMap["guard_zone_name"] = guardZoneName
			itemMap["state"] = "available"
			for _, entranceID := range enterprisePark.EntrancesFrozen {
				if entranceID == item.RecordID {
					itemMap["state"] = "unavailable"
				}
			}
			resultArray = append(resultArray, itemMap)
		}
	}
	return ctx.ResSuccess(resultArray)
}

// FreezeEntrance 冻结门禁设备
func (a *EPController) FreezeEntrance(ctx *context.Context) error {
	ctx.WriteOperateLog("EPController.FreezeEntrance", "企业门禁管理-冻结门禁设备")

	var (
		freezeParams *schema.FreezeParams
		err          error
	)

	freezeParams = new(schema.FreezeParams)
	if err = ctx.ParseJSON(freezeParams); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err = a.EnterpriseParkBll.FreezeEntrance(freezeParams)

	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}

// UnfreezeEntrance 解冻门禁设备
func (a *EPController) UnfreezeEntrance(ctx *context.Context) error {
	ctx.WriteOperateLog("EPController.UnfreezeEntrance", "企业门禁管理-解冻门禁设备")

	var (
		freezeParams *schema.FreezeParams
		err          error
	)

	freezeParams = new(schema.FreezeParams)
	if err = ctx.ParseJSON(freezeParams); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	err = a.EnterpriseParkBll.UnfreezeEntrance(freezeParams)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	return ctx.ResOK()
}
